package com.xiaoshuidi.cloud.module.report.service.datamanage;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.xiaoshuidi.cloud.module.report.controller.datamanage.vo.*;
import com.xiaoshuidi.cloud.module.report.dal.mapper.datamanage.LeaseAnalysisMapper;
import com.xiaoshuidi.cloud.module.report.utils.ApartmentUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDate;
import java.time.temporal.ChronoUnit;
import java.util.*;
import java.util.stream.Collectors;

@Slf4j
@Service
public class LeaseAnalysisServiceImpl implements LeaseAnalysisService {
    @Resource
    private LeaseAnalysisMapper leaseAnalysisMapper;

    @Resource
    private ApartmentUtils apartmentUtils;



    /**
     * 租赁合同分析
     *
     * @param vo
     * @return
     */
    @Override
    public List<LeaseContractAnalysisRespVO> leaseContractAnalysis(LeaseAnalysisReqVO vo) {
        vo.setApartmentIds(apartmentUtils.getAllIdsWhenIdsIsNull(vo.getApartmentIds()));
        List<String> yearMonthList = getYearMonthList(vo);
        List<LeaseContractAnalysisRespVO> ownerContractAnalysisRespVOS = leaseAnalysisMapper.leaseContractAnalysis(vo);
        return yearMonthList.stream().map(m->{
            LeaseContractAnalysisRespVO chartRespVO = new LeaseContractAnalysisRespVO();
            chartRespVO.setAnalysisTime(m);
            ownerContractAnalysisRespVOS.stream().filter(f->f.getAnalysisTime().equals(m)).findFirst().ifPresent(p->{
                chartRespVO.setNewCount(p.getNewCount());
                chartRespVO.setRenewalCount(p.getRenewalCount());
                chartRespVO.setNormalRentingCount(p.getNormalRentingCount());
                chartRespVO.setConsultRentingCount(p.getConsultRentingCount());
                chartRespVO.setBreachRentingCount(p.getBreachRentingCount());
            });
            return chartRespVO;
        }).collect(Collectors.toList());
    }


    /**
     * 租客签约分析
     *
     * @param vo
     * @return
     */
    @Override
    public LeaseSignContractRespVO leaseSignContractsAnalysis(LeaseAnalysisReqVO vo) {
        vo.setApartmentIds(apartmentUtils.getAllIdsWhenIdsIsNull(vo.getApartmentIds()));
        List<String> yearMonthList = getYearMonthList(vo);
        //获取分析数据
        List<LeaseSignContractsCountVO> list =
                leaseAnalysisMapper.leaseSignContractsAnalysis(vo);
        LeaseSignContractRespVO signContractsVO = new LeaseSignContractRespVO();
        long totalLeaseCount =
                list.stream().mapToLong(LeaseSignContractsCountVO::getLeaseCount).sum();
        long totalLeaseDuration =
                list.stream().mapToLong(LeaseSignContractsCountVO::getLeaseDuration).sum();
        signContractsVO.setTotalCount(totalLeaseCount);
        //计算评价数据
        if (totalLeaseCount > 0) {
            signContractsVO.setAverageLeaseTerm(totalLeaseDuration / totalLeaseCount);
        }
        signContractsVO.setColumnChartRespVOS(yearMonthList.stream().map(m->{
            LeaseSignContractRespVO.ColumnChartRespVO chartRespVO = new LeaseSignContractRespVO.ColumnChartRespVO();
            chartRespVO.setName(m);
            list.stream().filter(f->f.getAnalysisTime().equals(m)).findFirst().ifPresent(p->{
                chartRespVO.setValue(p.getLeaseCount());
            });
            return chartRespVO;
        }).collect(Collectors.toList()));

        return signContractsVO;
    }

    /**
     * 租客签约分析 -> 租期时长
     *
     * @param vo
     * @return
     */
    @Override
    public LinkedHashMap<String, Long> leasePeriodAnalysis(LeaseAnalysisReqVO vo) {
        vo.setApartmentIds(apartmentUtils.getAllIdsWhenIdsIsNull(vo.getApartmentIds()));
        return leaseAnalysisMapper.leasePeriodAnalysis(vo);
    }

    /**
     * 租客签约分析 -> 年龄分布
     *
     * @param vo
     * @return
     */
    @Override
    public LinkedHashMap<String, Long> leaseAgeAnalysis(LeaseAnalysisReqVO vo) {
        vo.setApartmentIds(apartmentUtils.getAllIdsWhenIdsIsNull(vo.getApartmentIds()));
        return leaseAnalysisMapper.leaseAgeAnalysis(vo);
    }

    /**
     * 业主合同分析
     *
     * @param vo
     * @return
     */
    @Override
    public List<OwnerContractAnalysisRespVO> ownerContractAnalysis(OwnerAnalysisReqVO vo) {
        vo.setApartmentIds(apartmentUtils.getAllIdsWhenIdsIsNull(vo.getApartmentIds()));
        List<String> yearMonthList = getYearMonthList(vo);
        List<OwnerContractAnalysisRespVO> ownerContractAnalysisRespVOS = leaseAnalysisMapper.ownerContractAnalysis(vo);
        return yearMonthList.stream().map(m->{
            OwnerContractAnalysisRespVO chartRespVO = new OwnerContractAnalysisRespVO();
            chartRespVO.setAnalysisTime(m);
            ownerContractAnalysisRespVOS.stream().filter(f->f.getAnalysisTime().equals(m)).findFirst().ifPresent(p->{
                chartRespVO.setNewCount(p.getNewCount());
                chartRespVO.setRenewalCount(p.getRenewalCount());
                chartRespVO.setExpireCount(p.getExpireCount());
                chartRespVO.setHalfwayCount(p.getHalfwayCount());
            });
            return chartRespVO;
        }).collect(Collectors.toList());
    }

    /**
     * 业主签约分析
     *
     * @param vo
     * @return
     */
    @Override
    public OwnersSignContractRespVO ownersSignContractsAnalysis(OwnerAnalysisReqVO vo) {
        vo.setApartmentIds(apartmentUtils.getAllIdsWhenIdsIsNull(vo.getApartmentIds()));
        List<String> yearMonthList = getYearMonthList(vo);
        //获取分析数据
        List<OwnersSignContractsCountVO> ownersSignContractsCountVOS =
                leaseAnalysisMapper.ownersSignContractsAnalysis(vo);
        OwnersSignContractRespVO signContractsVO = new OwnersSignContractRespVO();
        long totalOwnerCount =
                ownersSignContractsCountVOS.stream().mapToLong(OwnersSignContractsCountVO::getOwnerCount).sum();
        long totalLeaseDuration =
                ownersSignContractsCountVOS.stream().mapToLong(OwnersSignContractsCountVO::getLeaseDuration).sum();
        signContractsVO.setTotalCount(totalOwnerCount);
        //计算评价数据
        if (totalOwnerCount > 0) {
            signContractsVO.setAverageLeaseTerm(totalLeaseDuration / totalOwnerCount);
        }
        signContractsVO.setColumnChartRespVOS(yearMonthList.stream().map(m->{
            OwnersSignContractRespVO.ColumnChartRespVO chartRespVO = new OwnersSignContractRespVO.ColumnChartRespVO();
            chartRespVO.setName(m);
            ownersSignContractsCountVOS.stream().filter(f->f.getAnalysisTime().equals(m)).findFirst().ifPresent(p->{
                chartRespVO.setValue(p.getOwnerCount());
            });
            return chartRespVO;
        }).collect(Collectors.toList()));

        return signContractsVO;
    }

    /**
     * 业主年龄分析
     *
     * @param vo
     * @return
     */
    @Override
    public LinkedHashMap<String, Long> ownersAgeAnalysis(OwnerAnalysisReqVO vo) {
        vo.setApartmentIds(apartmentUtils.getAllIdsWhenIdsIsNull(vo.getApartmentIds()));
        getYearMonthList(vo);
        return leaseAnalysisMapper.ownersAgeAnalysis(vo);
    }



    /**
     * 业主租期时长分析
     *
     * @param vo
     * @return
     */
    @Override
    public LinkedHashMap<String, Long> ownersPeriodAnalysis(OwnerAnalysisReqVO vo) {
        vo.setApartmentIds(apartmentUtils.getAllIdsWhenIdsIsNull(vo.getApartmentIds()));
        vo.setApartmentIds(apartmentUtils.getAllIdsWhenIdsIsNull(vo.getApartmentIds()));
        getYearMonthList(vo);
        return leaseAnalysisMapper.ownersPeriodAnalysis(vo);
    }


    public static List<String> getYearMonthList(OwnerAnalysisReqVO vo) {
        long pe = 6;
        LocalDate localDate = LocalDate.now();
        //时间范围为空 默认取今日起6个月前的数据
        if (StrUtil.isNotEmpty(vo.getStartTimeStr()) && StrUtil.isNotEmpty(vo.getEndTimeStr())) {
            LocalDate startLocalDate = DateUtil.parseLocalDateTime(vo.getStartTimeStr(), "yyyy-MM").toLocalDate();
            LocalDate endLocalDate = DateUtil.parseLocalDateTime(vo.getEndTimeStr(), "yyyy-MM").toLocalDate();
            pe = ChronoUnit.MONTHS.between(startLocalDate, endLocalDate);
        }
        List<String> yearMonthList = getYearMonthList(localDate, pe);
        log.info("日期集合列表={}", yearMonthList);
        //写入开始时间
        vo.setStartTimeStr(yearMonthList.get(0));
        //写入结束时间
        vo.setEndTimeStr(yearMonthList.get(yearMonthList.size() - 1));
        return yearMonthList;
    }

    public static List<String> getYearMonthList(LocalDate today, long pe) {
        List<String> yearMonths = new ArrayList<>();
        for (int i = 0; i <= pe; i++) {
            LocalDate localDate = today.minusMonths(i);
            String yearMonth = localDate.toString().substring(0, 7);
            yearMonths.add(yearMonth);
        }
        //倒序
        Collections.reverse(yearMonths);
        return yearMonths;
    }
}
